import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layout/LayoutIndex.vue'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', component: Layout },
    { path: '/login', component: () => import('@/views/login/IndeView.vue') },
  ],
})

const list = ['/', '/layout']
// 路由拦截器
router.beforeEach((to, from, next) => {
  // 获取token
  const user = useUserStore()
  let token = user.userInfo.token
  if (list.includes(to.path)) {
    // 拦截
    if (!token) {
      // 无token
      // 回去登录
      next('/login')
    } else {
      next()
    }
  } else {
    // 不需要token
    next()
  }
})

export default router
